package com.ccteam.fluidmusic.ui.playlist.select

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.paging.LoadState
import com.ccteam.fluidmusic.databinding.FragmentSearchResultMusicBinding
import com.ccteam.fluidmusic.utils.EventObserver
import com.ccteam.fluidmusic.view.adapters.AddMediaCallback
import com.ccteam.fluidmusic.view.adapters.AddOnlineMediaPagerAdapter
import com.ccteam.fluidmusic.view.adapters.paging.CustomLoadStateAdapter
import com.ccteam.fluidmusic.view.bean.LoadMessage
import com.ccteam.fluidmusic.widget.SNACKBAR_PLAY_BAR
import com.ccteam.fluidmusic.widget.snackbar
import com.ccteam.fluidmusic.ui.search.SEARCH_KEY
import com.ccteam.shared.result.playlistsheet.AddMediaItem
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

/**
 * @author Xiaoc
 * @since 2021/3/17
 *
 * 添加歌曲到播放列表的显示歌曲信息的Fragment
 */
@AndroidEntryPoint
class AddOnlineMusicPagerFragment: Fragment() {

    private var _binding: FragmentSearchResultMusicBinding? = null
    private val binding: FragmentSearchResultMusicBinding get() = _binding!!

    private val addOnlineMusicViewModel by viewModels<AddOnlineMusicPagerViewModel>()

    private val addOnlineMediaViewModel by viewModels<AddOnlineMediaViewModel>(ownerProducer = { parentFragment ?: this })

    companion object{
        @JvmStatic
        fun newInstance(searchKey: String): AddOnlineMusicPagerFragment {
            return AddOnlineMusicPagerFragment().apply {
                arguments = Bundle().apply {
                    putString(SEARCH_KEY, searchKey)
                }
            }
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentSearchResultMusicBinding.inflate(inflater,container,false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {

        val dataAdapter = AddOnlineMediaPagerAdapter(callback)
        binding.rvMusicList.adapter = dataAdapter.withLoadStateFooter(
            CustomLoadStateAdapter(dataAdapter,true){
                dataAdapter.retry()
            }
        )

        viewLifecycleOwner.lifecycleScope.launch {
            addOnlineMusicViewModel.musicList.collectLatest {
                dataAdapter.submitData(it)
            }
        }

        viewLifecycleOwner.lifecycleScope.launch {
            dataAdapter.loadStateFlow.collectLatest { state ->
                binding.statusView.changeToLoadingStatus(state.refresh is LoadState.Loading)
                binding.statusView.changeToErrorStatus(state.refresh,
                    state.append.endOfPaginationReached && dataAdapter.itemCount < 1)
            }
        }

        /**
         * 观察添加歌曲到播放列表提示信息
         */
        if(addOnlineMediaViewModel.type == AddOnlineMediaFragment.TYPE_ADD_MUSIC_PLAYLIST){
            addOnlineMediaViewModel.addMusicToPlaylistLoadMessage.observe(viewLifecycleOwner, EventObserver{
                if(it is LoadMessage.Error){
                    view.snackbar(it.errorMessage.description.toString(), SNACKBAR_PLAY_BAR).show()
                } else if(it is LoadMessage.NotLoading){
                    view.snackbar("添加成功", SNACKBAR_PLAY_BAR).show()
                }
            })
        }
    }

    private val callback = object: AddMediaCallback{

        override fun itemClick(item: AddMediaItem) {
            if(addOnlineMediaViewModel.type == AddOnlineMediaFragment.TYPE_ADD_MUSIC_PLAYLIST){
                addOnlineMediaViewModel.addMusicToPlaylist(item)
            }
        }

    }

    override fun onDestroyView() {
        super.onDestroyView()

        _binding = null
    }
}